<template>
  <div class="main">
    <section class="sign-in-container">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="签到页设置" name="page">
          <activity-edit ref="page" :activityId="listQuery.activitySignInId"/>
        </el-tab-pane>
        <el-tab-pane label="签到设置" name="rules">
          <div v-if="rightsButtons['add']" class="btns-container">
            <el-button type="success" size="small" icon="el-icon-circle-plus" plain @click="btnClick('', 'add')">新建签到奖励规则</el-button>
          </div>
          <search-form :listQuery="listQuery" :queryConfig="queryConfig" :labelWidth="100" :search="search"/>
          <el-table :data="list" v-loading="listLoading" header-row-class-name="table-header" element-loading-text="给我一点时间" :row-class-name="tableRowClassName" border highlight-current-row>
            <el-table-column align="center" label="活动时间" prop="startDate" min-width="320">
              <template slot-scope="scope" v-if="scope.row.startDate">
                {{formatDate(scope.row.startDate, 'YYYY-MM-DD HH:mm:ss')}} 至 {{formatDate(scope.row.endDate, 'YYYY-MM-DD HH:mm:ss')}}
              </template>
            </el-table-column>
            <el-table-column align="center" label="状态" prop="responseStatus" min-width="160">
              <template slot-scope="scope">
                {{['', '未开始', '进行中', '','已结束'][scope.row.responseStatus]}}
              </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" prop="createAt" min-width="160">
              <template slot-scope="scope">
                {{formatDate(scope.row.createAt, 'YYYY-MM-DD HH:mm:ss')}}
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" prop="responseStatus" width="200" v-if="rightsButtons['view']||rightsButtons['edit']||rightsButtons['stop']||rightsButtons['copy']">
              <template slot-scope="scope">
                <el-button type="text" v-if="rightsButtons['view']"  @click="btnClick(scope.row, 'View')">查看</el-button>
                <el-button type="text" v-if="rightsButtons['edit'] && scope.row.responseStatus===1" @click="btnClick(scope.row, 'Edit')">编辑</el-button>
                <el-button type="text" v-if="rightsButtons['stop'] && scope.row.responseStatus < 3" @click="btnClick(scope.row, 'stop')">停止</el-button>
                <el-button type="text" v-if="rightsButtons['copy']" @click="btnClick(scope.row, 'copy')">复制</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="listQuery.pageIndex"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="listQuery.pageSize"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal">
          </el-pagination>
        </el-tab-pane>
        <el-tab-pane label="签到统计" name="statistics">
          <activity-statistics ref="statistics" :activityId="listQuery.activitySignInId"/>
        </el-tab-pane>
      </el-tabs>
    </section>
  </div>
</template>
<script>
import searchForm from '@/components/searchForm'
import activityEdit from './activityEdit'
import activityStatistics from './statistics'
export default {
  name: 'signIn',
  components: {
    searchForm,
    activityEdit,
    activityStatistics
  },
  data(){
    // const statusData = ['', '未开始', '进行中', '已停止', '已结束']
    const statusData = [
      { value: null, label: '全部' },
      { value: 1, label: '未开始' },
      { value: 2, label: '进行中' },
      { value: 4, label: '已结束' }
    ]
    return {
      activeName: 'rules',
      statusData,
      queryConfig: [
        { type:'daterange', label: '时间', prop: 'createDate', timestamp: true },
        { type:'select', label: '状态', prop: 'status', data: statusData }
      ],
      listLoading: false,
      listQuery: {
        createDate: [],
        activitySignInId: 2, //签到活动ID
        status: null,
        pageIndex: 1,
        pageSize: 20
      },
      list: [],
      listTotal: 0
    }
  },
  created(){
    if (this.$store.getters.cachedViews.length === 0) this.fetchData()
  },
  activated(){
    this.fetchData()
  },
  methods: {
    fetchData(){
      this.listLoading = true;
      let flag = this.listQuery.createDate && this.listQuery.createDate.length
      this.listQuery.startDate = flag ? this.listQuery.createDate[0] : '';
      this.listQuery.endDate = flag ? this.listQuery.createDate[1] : '';
      this.request({
        url: "/sign-in/rule/list",
        method: "post",
        data: this.listQuery
      }).then(({ data, totalCount }) => {
          this.list = data;
          this.listTotal = totalCount;
          this.listLoading = false;
        })
        .catch(err => {
          console.log(err);
          this.list = [];
          this.listTotal = 0;
          this.listLoading = false;
        });
    },
    search(){
      this.listQuery.pageIndex = 1
      this.fetchData()
    },
    handleSizeChange (value) {
      this.listQuery.pageIndex = 1
      this.listQuery.pageSize = value;
      this.fetchData()
    },
    handleCurrentChange(val){
      this.listQuery.pageIndex = val;
      this.fetchData();
    },
    handleClick(tab, event) {
      if (this.activeName !== 'rules' && this.$refs[this.activeName]) {
        this.$refs[this.activeName].fetchData()
      }
    },
    tableRowClassName({row}){
      if (row.responseStatus === 2) {
        return 'active-row';
      }
      return '';
    },
    btnClick(item, functionType) {
      if(functionType==='stop'){
        //
        this.$confirm('确定停止该活动, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.request({
            url: "/sign-in/rule/stop",
            method: "post",
            data: {
              activitySignInId: this.listQuery.activitySignInId,
              id: item.id
            }
          }).then(() => {
            this.$message.success('停止成功')
            this.fetchData()
          })
          .catch(err => {
            console.log(err);
          });
        });
      } else if (functionType==='add') {
        sessionStorage.removeItem('signinData')
        this.$router.push({name: 'signInAdd', params: { activitySignInId: this.listQuery.activitySignInId }})
      }
      else if (functionType==='copy') {
        this.request({
          url: '/sign-in/rule/detail',
          method: 'post',
          data: {
            activitySignInId: item.activitySignInId,
            id: item.id
          }
        }).then((res) => {
          if (res.status === 200 && res.data) {
            sessionStorage.setItem('signinData', JSON.stringify({ ...res.data, id: ''}))
          } else {
            sessionStorage.removeItem('signinData')
          }
        }).catch(err => {
          console.log(err)
        })
        this.$router.push({name: 'signInAdd', params: { activitySignInId: this.listQuery.activitySignInId }})
      } else {
        this.$router.push({
          name: `signIn${functionType}`,
          params: {
            id: item.id,
            activitySignInId: item.activitySignInId
          }
        })
      }
    }
  }
}
</script>
<style lang="scss">
.sign-in-container{
  min-height: 600px;
  .btns-container{
    padding-top: 12px;
    margin-bottom: 24px;
  }
  .active-row{
    color: rgb(30, 190, 30);
  }
}
</style>
